import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import Login from '@/views/Login.vue';
import type { UserInfo } from '@/types/index.js';

// 类型守卫：验证用户信息格式
const isUserInfo = (obj: unknown): obj is UserInfo => {
  return obj !== null 
    && typeof obj === 'object' 
    && 'role' in obj 
    && typeof (obj as UserInfo).role === 'string';
};

// 异步加载组件
const MerchantHome = () => import('@/views/MerchantHome.vue');
const UserHome = () => import('@/views/UserHome.vue');
const TeacherManage = () => import('@/views/TeacherManage.vue');
const DishManage = () => import('@/views/DishManage.vue');
const Reconciliation = () => import('@/views/Reconciliation.vue');

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/admin/merchants',
    component: () => import('@/views/MerchantManage.vue')
  },
  {
    path: '/admin/finance',
    component: () => import('@/views/FinanceReconciliation.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  
  // 商家相关路由
  {
    path: '/merchant/manage',
    name: 'MerchantHome',
    component: MerchantHome,
    meta: { requiresAuth: true, roles: ['商家'] }
  },
  {
    path: '/merchant/dishes',
    name: 'DishManage',
    component: DishManage,
    meta: { requiresAuth: true, roles: ['商家'] }
  },
  {
    path: '/merchant/reconciliation',
    name: 'Reconciliation',
    component: Reconciliation,
    meta: { requiresAuth: true, roles: ['商家'] }
  },
  
  // 教职工/管理员相关路由
  {
    path: '/user',
    name: 'UserHome',
    component: UserHome,
    meta: { requiresAuth: true, roles: ['教职工'] }
  },
  {
    path: '/user/teachers',
    name: 'TeacherManage',
    component: TeacherManage,
    meta: { requiresAuth: true, roles: ['管理员', '教职工'] }
  },
  
  // 根路径与未匹配路径处理
  { path: '/', redirect: '/login' },
  { path: '/:pathMatch(.*)*', redirect: '/login' }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const requiresAuth = to.meta.requiresAuth;
  const token = localStorage.getItem('token');
  const hasToken = !!token;

  // 解析本地用户信息
  let user: unknown = null;
  try {
    const userStr = localStorage.getItem('user');
    if (userStr) {
      user = JSON.parse(userStr);
    }
  } catch (error) {
    console.error('解析用户信息失败：', error);
    localStorage.removeItem('user');
    user = null;
  }

  // 处理需要授权的页面
  if (requiresAuth) {
    if (!hasToken || !isUserInfo(user)) {
      next(`/login?redirect=${to.fullPath}`);
    } else {
      const allowedRoles = to.meta.roles as string[];
      if (allowedRoles.includes(user.role)) {
        next();
      } else {
        // 角色不匹配时的跳转
        switch (user.role) {
          case '管理员':
            next('/user/teachers');
            break;
          case '商家':
            next('/merchant/manage');
            break;
          case '教职工':
            next('/user');
            break;
          default:
            next('/login');
        }
      }
    }
  } else {
    // 处理不需要授权的页面
    if (hasToken && isUserInfo(user)) {
      // 已登录用户访问登录页，直接跳转到对应角色首页
      switch (user.role) {
        case '管理员':
          next('/user/teachers');
          break;
        case '商家':
          next('/merchant/manage');
          break;
        case '教职工':
          next('/user');
          break;
        default:
          next();
      }
    } else {
      next();
    }
  }
});

export default router;